home *** CD-ROM | disk | FTP | other *** search
/ Graphics Plus / Graphics Plus.iso / general / procssng / ccs / ccs-11tl.lha / lbl / sun / jpeg / lib / jdhuff.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-02-26  |  12.3 KB  |  419 lines

  1. /*
  2.  * jdhuff.c
  3.  *
  4.  * Copyright (C) 1991, 1992, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains Huffman entropy decoding routines.
  9.  * These routines are invoked via the methods entropy_decode
  10.  * and entropy_decode_init/term.
  11.  */
  12.  
  13. #include "jinclude.h"
  14.  
  15.  
  16. /* Static variables to avoid passing 'round extra parameters */
  17.  
  18. static decompress_info_ptr dcinfo;
  19.  
  20. static INT32 get_buffer;    /* current bit-extraction buffer */
  21. static int bits_left;        /* # of unused bits in it */
  22. static boolean printed_eod;    /* flag to suppress multiple end-of-data msgs */
  23.  
  24. LOCAL void
  25. fix_huff_tbl (HUFF_TBL * htbl)
  26. /* Compute derived values for a Huffman table */
  27. {
  28.   int p, i, l, si;
  29.   char huffsize[257];
  30.   UINT16 huffcode[257];
  31.   UINT16 code;
  32.   
  33.   /* Figure C.1: make table of Huffman code length for each symbol */
  34.   /* Note that this is in code-length order. */
  35.  
  36.   p = 0;
  37.   for (l = 1; l <= 16; l++) {
  38.     for (i = 1; i <= (int) htbl->bits[l]; i++)
  39.       huffsize[p++] = (char) l;
  40.   }
  41.   huffsize[p] = 0;
  42.   
  43.   /* Figure C.2: generate the codes themselves */
  44.   /* Note that this is in code-length order. */
  45.   
  46.   code = 0;
  47.   si = huffsize[0];
  48.   p = 0;
  49.   while (huffsize[p]) {
  50.     while (((int) huffsize[p]) == si) {
  51.       huffcode[p++] = code;
  52.       code++;
  53.     }
  54.     code <<= 1;
  55.     si++;
  56.   }
  57.  
  58.   /* We don't bother to fill in the encoding tables ehufco[] and ehufsi[], */
  59.   /* since they are not used for decoding. */
  60.  
  61.   /* Figure F.15: generate decoding tables */
  62.  
  63.   p = 0;
  64.   for (l = 1; l <= 16; l++) {
  65.     if (htbl->bits[l]) {
  66.       htbl->valptr[l] = p;    /* huffval[] index of 1st sym of code len l */
  67.       htbl->mincode[l] = huffcode[p]; /* minimum code of length l */
  68.       p += htbl->bits[l];
  69.       htbl->maxcode[l] = huffcode[p-1];    /* maximum code of length l */
  70.     } else {
  71.       htbl->maxcode[l] = -1;
  72.     }
  73.   }
  74.   htbl->maxcode[17] = 0xFFFFFL;    /* ensures huff_DECODE terminates */
  75. }
  76.  
  77.  
  78. /*
  79.  * Code for extracting the next N bits from the input stream.
  80.  * (N never exceeds 15 for JPEG data.)
  81.  * This needs to go as fast as possible!
  82.  *
  83.  * We read source bytes into get_buffer and dole out bits as needed.
  84.  * If get_buffer already contains enough bits, they are fetched in-line
  85.  * by the macros get_bits() and get_bit().  When there aren't enough bits,
  86.  * fill_bit_buffer is called; it will attempt to fill get_buffer to the
  87.  * "high water mark", then extract the desired number of bits.  The idea,
  88.  * of course, is to minimize the function-call overhead cost of entering
  89.  * fill_bit_buffer.
  90.  * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  91.  * of get_buffer to be used.  (On machines with wider words, an even larger
  92.  * buffer could be used.)  However, on some machines 32-bit shifts are
  93.  * relatively slow and take time proportional to the number of places shifted.
  94.  * (This is true with most PC compilers, for instance.)  In this case it may
  95.  * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
  96.  * average shift distance at the cost of more calls to fill_bit_buffer.
  97.  */
  98.  
  99. #ifdef SLOW_SHIFT_32
  100. #define MIN_GET_BITS  15    /* minimum allowable value */
  101. #else
  102. #define MIN_GET_BITS  25    /* max value for 32-bit get_buffer */
  103. #endif
  104.  
  105. static const int bmask[16] =    /* bmask[n] is mask for n rightmost bits */
  106.   { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  107.     0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
  108.  
  109.  
  110. LOCAL int
  111. fill_bit_buffer (int nbits)
  112. /* Load up the bit buffer and do get_bits(nbits) */
  113. {
  114.   /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  115.   while (bits_left < MIN_GET_BITS) {
  116.     register int c = JGETC(dcinfo);
  117.     
  118.     /* If it's 0xFF, check and discard stuffed zero byte */
  119.     if (c == 0xFF) {
  120.       int c2 = JGETC(dcinfo);
  121.       if (c2 != 0) {
  122.     if (c2 != 0xd9)    {    /* M_EOI is extra    */
  123.     /* Oops, it's actually a marker indicating end of compressed data. */
  124.     /* Better put it back for use later */
  125.         JUNGETC(c2,dcinfo);
  126.         JUNGETC(c,dcinfo);
  127.     }
  128.     /* There should be enough bits still left in the data segment; */
  129.     /* if so, just break out of the while loop. */
  130.     if (bits_left >= nbits)
  131.       break;
  132.     /* Uh-oh.  Report corrupted data to user and stuff zeroes into
  133.      * the data stream, so we can produce some kind of image.
  134.      * Note that this will be repeated for each byte demanded for the
  135.      * rest of the segment; this is a bit slow but not unreasonably so.
  136.      * The main thing is to avoid getting a zillion warnings, hence:
  137.      */
  138.     if (! printed_eod) {
  139.       WARNMS2(dcinfo->emethods, "Corrupt JPEG data: premature end of data segment %x %X", ftell(dinfo.input_file), c2);
  140.       printed_eod = TRUE;
  141.     }
  142.     c = 0;            /* insert a zero byte into bit buffer */
  143.       }
  144.     }
  145.  
  146.     /* OK, load c into get_buffer */
  147.     get_buffer = (get_buffer << 8) | c;
  148.     bits_left += 8;
  149.   }
  150.  
  151.   /* Having filled get_buffer, extract desired bits (this simplifies macros) */
  152.   bits_left -= nbits;
  153.   return ((int) (get_buffer >> bits_left)) & bmask[nbits];
  154. }
  155.  
  156.  
  157. /* Macros to make things go at some speed! */
  158. /* NB: parameter to get_bits should be simple variable, not expression */
  159.  
  160. #define get_bits(nbits) \
  161.     (bits_left >= (nbits) ? \
  162.      ((int) (get_buffer >> (bits_left -= (nbits)))) & bmask[nbits] : \
  163.      fill_bit_buffer(nbits))
  164.  
  165. #define get_bit() \
  166.     (bits_left ? \
  167.      ((int) (get_buffer >> (--bits_left))) & 1 : \
  168.      fill_bit_buffer(1))
  169.  
  170.  
  171. /* Figure F.16: extract next coded symbol from input stream */
  172.   
  173. INLINE
  174. LOCAL int
  175. huff_DECODE (HUFF_TBL * htbl)
  176. {
  177.   register int l;
  178.   register INT32 code;
  179.   
  180.   code = get_bit();
  181.   l = 1;
  182.   while (code > htbl->maxcode[l]) {
  183.     code = (code << 1) | get_bit();
  184.     l++;
  185.   }
  186.  
  187.   /* With garbage input we may reach the sentinel value l = 17. */
  188.  
  189.   if (l > 16) {
  190.     WARNMS(dcinfo->emethods, "Corrupt JPEG data: bad Huffman code");
  191.     return 0;            /* fake a zero as the safest result */
  192.   }
  193.  
  194.   return htbl->huffval[ htbl->valptr[l] + ((int) (code - htbl->mincode[l])) ];
  195. }
  196.  
  197.  
  198. /* Figure F.12: extend sign bit */
  199.  
  200. #define huff_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  201.  
  202. static const int extend_test[16] =   /* entry n is 2**(n-1) */
  203.   { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  204.     0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  205.  
  206. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  207.   { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  208.     ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  209.     ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  210.     ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  211.  
  212.  
  213. /*
  214.  * Initialize for a Huffman-compressed scan.
  215.  * This is invoked after reading the SOS marker.
  216.  */
  217.  
  218. METHODDEF void
  219. huff_decoder_init (decompress_info_ptr cinfo)
  220. {
  221.   short ci;
  222.   jpeg_component_info * compptr;
  223.  
  224.   /* Initialize static variables */
  225.   dcinfo = cinfo;
  226.   bits_left = 0;
  227.   printed_eod = FALSE;
  228.  
  229.   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  230.     compptr = cinfo->cur_comp_info[ci];
  231.     /* Make sure requested tables are present */
  232.     if (cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no] == NULL ||
  233.     cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no] == NULL)
  234.       ERREXIT(cinfo->emethods, "Use of undefined Huffman table");
  235.     /* Compute derived values for Huffman tables */
  236.     /* We may do this more than once for same table, but it's not a big deal */
  237.     fix_huff_tbl(cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no]);
  238.     fix_huff_tbl(cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no]);
  239.     /* Initialize DC predictions to 0 */
  240.     cinfo->last_dc_val[ci] = 0;
  241.   }
  242.  
  243.   /* Initialize restart stuff */
  244.   cinfo->restarts_to_go = cinfo->restart_interval;
  245.   cinfo->next_restart_num = 0;
  246. }
  247.  
  248.  
  249. /*
  250.  * Check for a restart marker & resynchronize decoder.
  251.  */
  252.  
  253. LOCAL void
  254. process_restart (decompress_info_ptr cinfo)
  255. {
  256.   int c, nbytes;
  257.   short ci;
  258.  
  259.   /* Throw away any unused bits remaining in bit buffer */
  260.   nbytes = bits_left / 8;    /* count any full bytes loaded into buffer */
  261.   bits_left = 0;
  262.   printed_eod = FALSE;        /* next segment can get another warning */
  263.  
  264.   /* Scan for next JPEG marker */
  265.   do {
  266.     do {            /* skip any non-FF bytes */
  267.       nbytes++;
  268.       c = JGETC(cinfo);
  269.     } while (c != 0xFF);
  270.     do {            /* skip any duplicate FFs */
  271.       /* we don't increment nbytes here since extra FFs are legal */
  272.       c = JGETC(cinfo);
  273.     } while (c == 0xFF);
  274.   } while (c == 0);        /* repeat if it was a stuffed FF/00 */
  275.  
  276.   if (nbytes != 1)
  277.     WARNMS2(cinfo->emethods,
  278.         "Corrupt JPEG data: %d extraneous bytes before marker 0x%02x",
  279.         nbytes-1, c);
  280.  
  281.   if (c != (RST0 + cinfo->next_restart_num)) {
  282.     /* Uh-oh, the restart markers have been messed up too. */
  283.     /* Let the file-format module try to figure out how to resync. */
  284.     (*cinfo->methods->resync_to_restart) (cinfo, c);
  285.   } else
  286.     TRACEMS1(cinfo->emethods, 2, "RST%d", cinfo->next_restart_num);
  287.  
  288.   /* Re-initialize DC predictions to 0 */
  289.   for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  290.     cinfo->last_dc_val[ci] = 0;
  291.  
  292.   /* Update restart state */
  293.   cinfo->restarts_to_go = cinfo->restart_interval;
  294.   cinfo->next_restart_num = (cinfo->next_restart_num + 1) & 7;
  295. }
  296.  
  297.  
  298. /* ZAG[i] is the natural-order position of the i'th element of zigzag order.
  299.  * If the incoming data is corrupted, huff_decode_mcu could attempt to
  300.  * reference values beyond the end of the array.  To avoid a wild store,
  301.  * we put some extra zeroes after the real entries.
  302.  */
  303.  
  304. static const short ZAG[DCTSIZE2+16] = {
  305.   0,  1,  8, 16,  9,  2,  3, 10,
  306.  17, 24, 32, 25, 18, 11,  4,  5,
  307.  12, 19, 26, 33, 40, 48, 41, 34,
  308.  27, 20, 13,  6,  7, 14, 21, 28,
  309.  35, 42, 49, 56, 57, 50, 43, 36,
  310.  29, 22, 15, 23, 30, 37, 44, 51,
  311.  58, 59, 52, 45, 38, 31, 39, 46,
  312.  53, 60, 61, 54, 47, 55, 62, 63,
  313.   0,  0,  0,  0,  0,  0,  0,  0, /* extra entries in case k>63 below */
  314.   0,  0,  0,  0,  0,  0,  0,  0
  315. };
  316.  
  317.  
  318. /*
  319.  * Decode and return one MCU's worth of Huffman-compressed coefficients.
  320.  * This routine also handles quantization descaling and zigzag reordering
  321.  * of coefficient values.
  322.  *
  323.  * The i'th block of the MCU is stored into the block pointed to by
  324.  * MCU_data[i].  WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  325.  * (Wholesale zeroing is usually a little faster than retail...)
  326.  */
  327.  
  328. METHODDEF void
  329. huff_decode_mcu (decompress_info_ptr cinfo, JBLOCKROW *MCU_data)
  330. {
  331.   register int s, k, r;
  332.   short blkn, ci;
  333.   register JBLOCKROW block;
  334.   register QUANT_TBL_PTR quanttbl;
  335.   HUFF_TBL *dctbl;
  336.   HUFF_TBL *actbl;
  337.   jpeg_component_info * compptr;
  338.  
  339.   /* Account for restart interval, process restart marker if needed */
  340.   if (cinfo->restart_interval) {
  341.     if (cinfo->restarts_to_go == 0)
  342.       process_restart(cinfo);
  343.     cinfo->restarts_to_go--;
  344.   }
  345.  
  346.   /* Outer loop handles each block in the MCU */
  347.  
  348.   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  349.     block = MCU_data[blkn];
  350.     ci = cinfo->MCU_membership[blkn];
  351.     compptr = cinfo->cur_comp_info[ci];
  352.     quanttbl = cinfo->quant_tbl_ptrs[compptr->quant_tbl_no];
  353.     actbl = cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no];
  354.     dctbl = cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no];
  355.  
  356.     /* Decode a single block's worth of coefficients */
  357.  
  358.     /* Section F.2.2.1: decode the DC coefficient difference */
  359.     s = huff_DECODE(dctbl);
  360.     if (s) {
  361.       r = get_bits(s);
  362.       s = huff_EXTEND(r, s);
  363.     }
  364.  
  365.     /* Convert DC difference to actual value, update last_dc_val */
  366.     s += cinfo->last_dc_val[ci];
  367.     cinfo->last_dc_val[ci] = (JCOEF) s;
  368.     /* Descale and output the DC coefficient (assumes ZAG[0] = 0) */
  369.     (*block)[0] = (JCOEF) (((JCOEF) s) * quanttbl[0]);
  370.     
  371.     /* Section F.2.2.2: decode the AC coefficients */
  372.     /* Since zero values are skipped, output area must be zeroed beforehand */
  373.     for (k = 1; k < DCTSIZE2; k++) {
  374.       r = huff_DECODE(actbl);
  375.       
  376.       s = r & 15;
  377.       r = r >> 4;
  378.       
  379.       if (s) {
  380.     k += r;
  381.     r = get_bits(s);
  382.     s = huff_EXTEND(r, s);
  383.     /* Descale coefficient and output in natural (dezigzagged) order */
  384.     (*block)[ZAG[k]] = (JCOEF) (((JCOEF) s) * quanttbl[k]);
  385.       } else {
  386.     if (r != 15)
  387.       break;
  388.     k += 15;
  389.       }
  390.     }
  391.   }
  392. }
  393.  
  394.  
  395. /*
  396.  * Finish up at the end of a Huffman-compressed scan.
  397.  */
  398.  
  399. METHODDEF void
  400. huff_decoder_term (decompress_info_ptr cinfo)
  401. {
  402.   /* No work needed */
  403. }
  404.  
  405.  
  406. /*
  407.  * The method selection routine for Huffman entropy decoding.
  408.  */
  409.  
  410. GLOBAL void
  411. jseldhuffman (decompress_info_ptr cinfo)
  412. {
  413.   if (! cinfo->arith_code) {
  414.     cinfo->methods->entropy_decode_init = huff_decoder_init;
  415.     cinfo->methods->entropy_decode = huff_decode_mcu;
  416.     cinfo->methods->entropy_decode_term = huff_decoder_term;
  417.   }
  418. }
  419.